var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var config = require('./config');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var course = require('./routes/course');
var user = require('./routes/user');
var info = require('./routes/info');
var order = require('./routes/order');
var data = require('./routes/data');

var compress = require('compression');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var cors = require('cors');

var app = express();

var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
//app.use(cookieParser());

app.use(session({
    store: new RedisStore({
        host: config.get('redis:host'),
        pass: config.get('redis:pass'),
        port: 6379,
        db: 3,
        ttl: 12 * 3600,
        prefix: 'sess'
    }),
    resave: false,
    saveUninitialized: false,
    secret: 'keyboard cat'
}));
app.use(cors());
app.use(compress());
app.use(express.static(path.join(__dirname, 'public')));
var multer = require('multer');
var upload = multer({ dest: './tmp/' });
//app.use(multer({dest: './tmp/'}));
app.use('/', routes);
app.use('/course', course);
app.use('/user', user);
app.use('/info', info);
app.use('/order', order);
app.use('/data', data);

//app.use('/course/detail', course.detail);
//app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});


module.exports = app;